package com.drinks.yiniang.utils;

import android.app.Activity;
import android.content.Context;
import android.graphics.Rect;
import android.os.Build;
import android.util.DisplayMetrics;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.EditText;
import android.widget.Toast;

import com.hansen.library.utils.LogUtils;

/**
 * @author han
 * @date 2019/12/9
 */
public class KeyboardPatch {
    private Activity activity;
    private View decorView;
    private View contentView;
    private int srcPaddingBottm;
    private boolean keyboardVisiable;
    private int screenHeight;
    /**
     * @param act         需要解决bug的activity
     * @param contentView 界面容器，最好是可滑动的View，比如ScrollView等
     */
    public KeyboardPatch(Activity act, View contentView) {
        this.activity = act;
        this.decorView = act.getWindow().getDecorView();
        this.contentView = contentView;
        srcPaddingBottm = contentView.getPaddingBottom();
        screenHeight = decorView.getContext().getResources().getDisplayMetrics().heightPixels;
    }

    /**
     * 监听layout变化
     */
    public void enable() {
        //activity.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        if (Build.VERSION.SDK_INT >= 19) {
            decorView.getViewTreeObserver().addOnGlobalLayoutListener(onGlobalLayoutListener);
        }
    }

    /**
     * 取消监听
     */
    public void disable() {
        if (Build.VERSION.SDK_INT >= 19) {
            decorView.getViewTreeObserver().removeOnGlobalLayoutListener(onGlobalLayoutListener);
        }
    }

    private ViewTreeObserver.OnGlobalLayoutListener onGlobalLayoutListener = new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            Rect r = new Rect();
            //获取可见窗口的frame，主要是获取r.bottom
            decorView.getWindowVisibleDisplayFrame(r);
            //判断软键盘是否弹起
            keyboardVisiable = screenHeight - r.bottom >= 0;
            //寻找获得焦点的view
            View focusView = decorView.findFocus();

            LogUtils.e("=================focusView==========" + (focusView != null ? focusView.toString() : ""));

            if (focusView != null && focusView instanceof EditText) {
                int[] location = new int[2];
                focusView.getLocationOnScreen(location);
                //如果focusView的高度很高的话，可以不必都显示出来
                int focusBottom = location[1] + focusView.getMeasuredHeight();
                //获取焦点的EditText的最底部和可见窗口的最底部的差值
                int diff = focusBottom - r.bottom;
                //如果大于0，说明被遮挡了，需要添加paddingBottom的值增加diff，并且需要把焦点view滑动上来，如果小于0，说明不存在遮挡，还原即可
                if (diff > 0) {
                    if (srcPaddingBottm != diff) {
                        contentView.setPadding(contentView.getPaddingLeft(), contentView.getPaddingTop(), contentView.getPaddingRight(), diff + srcPaddingBottm);
                        contentView.scrollBy(0, diff);
                    }
                } else {
                    LogUtils.e("------------------------------else 进入");
                    if (diff < 0 && contentView.getPaddingBottom() != 0) {
                        contentView.setPadding(contentView.getPaddingLeft(), contentView.getPaddingTop(), contentView.getPaddingRight(), srcPaddingBottm);
                    }
                }

                LogUtils.e("==================diff=" + diff);
                LogUtils.e("======getPaddingBottom=" + contentView.getPaddingBottom());
                LogUtils.e("==============location=" + location.toString());
            }

        }
    };

    private void setListenerToRootView(Activity activity) {
        final View rootView = activity.getWindow().getDecorView().findViewById(android.R.id.content);
        rootView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                boolean mKeyboardUp = isKeyboardShown(rootView);
                if (mKeyboardUp) {
                    //Toast.makeText(EdittextActivity.this, "键盘弹出", Toast.LENGTH_SHORT).show();
                } else {
                    //Toast.makeText(EdittextActivity.this, "键盘收起", Toast.LENGTH_SHORT).show();
                }
                //如果只想检测一次，需要注销
                //rootView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
            }
        });
    }

    private boolean isKeyboardShown(View rootView) {
        final int softKeyboardHeight = 100;
        Rect r = new Rect();
        rootView.getWindowVisibleDisplayFrame(r);
        DisplayMetrics dm = rootView.getResources().getDisplayMetrics();
        int heightDiff = rootView.getBottom() - r.bottom;
        return heightDiff > softKeyboardHeight * dm.density;
    }
}
